package m.store.task;

import com.alibaba.fastjson.JSONObject;
import m.common.action.Action;
import m.common.model.util.ModelQuery;
import m.common.model.util.ModelUpdate;
import m.common.model.util.QueryCondition;
import m.store.model.GoodsOutRecord;
import m.store.model.GoodsStockRecord;
import m.store.model.OrderModel;
import m.store.model.SaleInfo;
import m.system.db.TransactionManager;
import m.system.util.JSONMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

public class GoodsStockRecordSupport implements Runnable {
    private GoodsStockRecordSupport(){}
    private static boolean isRun=true;
    static Thread th;
    static final List<String[]> ls=new ArrayList<>();
    static String[] current=null;

    @Override
    public void run() {
        while (true){
            if(ls.isEmpty()){
                StoreGoodsSupport.start();
                StockInfoPaySupport.start();
                TransactionManager.closeConnection();
                LockSupport.park();
                TransactionManager.initConnection();
            }
            if(!isRun) break;
            if(!ls.isEmpty()){
                current=ls.remove(0);
                String recordOid=current[0];
                String stockOid=current[1];
                String goodsOid=current[2];
                StoreGoodsSupport.add(goodsOid);
                StockInfoPaySupport.add(stockOid);
                execute(recordOid,stockOid,goodsOid);
                current=null;
            }
        }
    }
    private void execute(String recordOid,String stockOid,String goodsOid){
        try {
            if(ls.size()<10) Thread.sleep(100L);
            Integer num= ModelQuery.init(GoodsStockRecord.class)
                .addCollectExp("num","ifnull(sum(#{stockNum}),0)")
                .addCondition(QueryCondition.and(
                    QueryCondition.eq("backRecord.oid",recordOid),
                    QueryCondition.le("stockNum",0)
                ))
                .queryCollect().get(0).getInteger("num");
            Double amount= ModelQuery.init(GoodsStockRecord.class)
                .addCollectExp("amount","ifnull(sum(#{stockAmount}),0)")
                .addCondition(QueryCondition.and(
                    QueryCondition.eq("backRecord.oid",recordOid),
                    QueryCondition.le("stockNum",0)
                ))
                .queryCollect().get(0).getDouble("amount");
            //更新入库明细冗余信息
            ModelUpdate.init(GoodsStockRecord.class)
            .set("refundNum", GoodsOutRecord.class, "ifnull(sum(#{num}),0)",
                QueryCondition.and(
                    QueryCondition.eq("record.oid", recordOid),
                    QueryCondition.eq("sale.refundStock.oid",stockOid),
                    QueryCondition.eq("sale.status", OrderModel.Status_Done)
                )
            )
            .set("refundAmount", GoodsOutRecord.class, "ifnull(sum(#{saleAmount}),0)",
                QueryCondition.and(
                    QueryCondition.eq("record.oid", recordOid),
                    QueryCondition.eq("sale.refundStock.oid",stockOid),
                    QueryCondition.eq("sale.status", OrderModel.Status_Done)
                )
            )
            .set("saleNum",GoodsOutRecord.class,"ifnull(sum(#{num}),0)",
                QueryCondition.and(
                    QueryCondition.eq("record.oid",recordOid),
                    QueryCondition.isEmpty("sale.refundStock.oid"),
                    QueryCondition.eq("sale.status", OrderModel.Status_Done)
                )
            )
            .setExp("surplusNum", "#{stockNum}-#{refundNum}-#{saleNum}+"+num)
            .setExp("surplusAmount", "round(#{stockAmount}-#{refundAmount}+"+amount+"-#{saleNum}*#{preferentialPrice},2)")
            .execute(recordOid);
        }catch (Exception e){
            Action.directLog("定时任务","更新入库明细冗余信息失败",this.getClass().getName(),
                    new JSONMessage().push("recordOid",recordOid).push("stockOid",stockOid).push("goodsOid",goodsOid).toJSONString(),e);
        }
    }
    /** 出库审核通过调用
     * 添加要更新的入库明细oid
     */
    public static void add(String record_oid,String stock_oid,String goods_oid){
        String[] arr=new String[]{record_oid,stock_oid,goods_oid};
        if(!ls.contains(arr)) {
            ls.add(arr);
        }
    }

    /**
     * 开始更新
     */
    public static void start(){
        if(null==th){
            th=new Thread(new GoodsStockRecordSupport());
            th.start();
        }else{
            LockSupport.unpark(th);
        }
    }

    public static void close(){
        isRun=false;
        LockSupport.unpark(th);
    }
    /**
     * 指定参数完成后跳出方法
     */
    protected static void doneHandler(String... goodsOids) throws InterruptedException {
        for(String oid : goodsOids){
            if(null!=current&&oid.equals(current[2])){
                Thread.sleep(30L);
                doneHandler(oid);
            }else {
                try {
                    for (String[] arr : ls) {
                        if (arr[2].equals(oid)) {
                            Thread.sleep(30L);
                            doneHandler(oid);
                        }
                    }
                }catch (Exception e){
                    doneHandler(goodsOids);
                }
            }
        }
    }
}
